package com.GLM.Viewer.Users;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.MsgEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.RefreshListView.XListView;
import com.GLM.Tools.Utils.RefreshListView.XListView.IXListViewListener;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Circle.CircleDetailMessageActivity;
import com.GLM.Viewer.Message.MessageDetailActivity;
import com.GLM.Viewer.Message.MessageMainActivity;
import com.google.gson.Gson;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class UserMessageActivity extends Activity implements  IXListViewListener{
	private final static int MESSAGE_LOADING = 111;
	private final static int MESSAGE_LONDED = 222;
	private XListView mListView;
	private SimpleAdapter mAdapter;
	private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();
	private int[] messageItemIds = new int[] { R.id.list_item_nickname, R.id.list_item_date, R.id.list_item_likecount, R.id.list_item_likicon, R.id.list_item_contents,R.id.list_item_messageid};
	private String[] messageItemKeys = new String[] {  "nickname", "date", "likecount", "likeicon", "contents","messageid" };
	private int mUserId;
	private int page = 1;
	private int ringid;
	private Button gobackButton;
//	private List<ReviewEntity> msgComments = new ArrayList<ReviewEntity>();
	private Map<String, String> messagesMap = new HashMap<String, String>();
	private Map<String, String> avatarsMap = new HashMap<String, String>();
	AsynImageLoader asynImageLoader = new AsynImageLoader();
	private ProgressBar mProgressBar;
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Thread thread;
			switch (msg.what) {
			case MESSAGE_LOADING:
				page = 1;
				mItems.clear();
				mListView.setAdapter(null);
				mProgressBar.setVisibility(View.VISIBLE);
				thread = new Thread(new Runnable() {
					public void run() {
						initUserMessage();
						mAdapter = new SimpleAdapter(UserMessageActivity.this, mItems, R.layout.xlistview_item_message, messageItemKeys, messageItemIds);
						mHandler.sendEmptyMessage(MESSAGE_LONDED);
					}
				});
				thread.start();
				break;

			case MESSAGE_LONDED:
				mProgressBar.setVisibility(View.GONE);
				
				onLoad();
				mListView.setAdapter(mAdapter);
				bindItemClick();
				break;
			}
		}
	};

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_user_message);
		
		Intent intent = getIntent();
		mUserId = intent.getIntExtra(Constant.INTENT_USER_ID, -1);
		initListView();
		mHandler.sendEmptyMessage(MESSAGE_LOADING);
	}

	private void initListView() {
		mProgressBar = (ProgressBar)findViewById(R.id.message_list_progressbar);
		if (mItems == null || mItems.size() == 0) {
			mHandler.sendEmptyMessage(MESSAGE_LOADING);
		}
		mListView = (XListView) findViewById(R.id.xListView);
		mListView.setPullLoadEnable(true);
		mListView.setXListViewListener(this);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
				MsgEntity entity = (MsgEntity) item.get("entity");
				Intent intent = new Intent(UserMessageActivity.this,MessageDetailActivity.class);
				intent.putExtra(Constant.MESSAGE_CURRENT_USERID, mUserId);
				intent.putExtra(Constant.MESSAGE_ENTITY, entity);
				startActivity(intent);
			}
		});
	}
	
	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime("刚刚");
	}
	
	public OnScrollListener  scrollListener = new OnScrollListener() {
		
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){
				
			}
		}
		
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			if(visibleItemCount >0 && totalItemCount >0){
				LoadPic();
			}
				
		}
	};
	
	
	public void bindItemClick(){
		mListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View v, int position,
					long arg3) {
				// TODO Auto-generated method stub
				HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
				MsgEntity entity = (MsgEntity) item.get("entity");
				Intent intent = new Intent(UserMessageActivity.this,MessageDetailActivity.class);
				intent.putExtra(Constant.MESSAGE_CURRENT_USERID, mUserId);
				intent.putExtra(Constant.MESSAGE_ENTITY, entity);
				startActivity(intent);
			}
		});
		mListView.setOnScrollListener(scrollListener);
	}
	
	public void initUserMessage(){
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String currentDate = sDateFormat.format(new java.util.Date());
		JSONObject request = new JSONObject();
		try {
			request.put("class", 2);
			request.put("msg_page", page);
			request.put("msg_date", currentDate);
			request.put("user_id", mUserId);
			JSONResponse jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETCIRCLEMESSAGE, request);
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					initMessageItemFromJSONObject(data.getJSONArray("msgData"));
				} else {
//					ViewsUtil.showErrorTip(UserMessageActivity.this, R.string.global_error_networkerr);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private void initMessageItemFromJSONObject(JSONArray jsonArray) throws JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			MsgEntity msgEntity = gson.fromJson(jsonArray.getJSONObject(i).toString(), MsgEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			String avatarPath = msgEntity.getMsg_user_avatar();
			item.put("nickname", msgEntity.getMsg_user_nickname());
			item.put("date", msgEntity.getMsg_date());
			if (0 == msgEntity.getMsg_viewCount()) {
				item.put("likeicon", R.drawable.glm_likeicon_dark);
			} else {
				item.put("likeicon", R.drawable.glm_likeicon_red);
			}
			item.put("likecount", String.format("Like: %d", msgEntity.getMsg_viewCount()));
			item.put("contents", msgEntity.getMsg_content());
			item.put("entity", msgEntity);
			item.put("messageid", msgEntity.getMsg_id());
			item.put("entity", msgEntity);
			mItems.add(item);
			avatarsMap.put(String.valueOf(msgEntity.getMsg_id()), avatarPath);
		
			String comPic = msgEntity.getMsg_picture();
			messagesMap.put(String.valueOf(msgEntity.getMsg_id()), comPic);
			
			
		}
	}
	
	public void goBackButton_OnClick(View v){
		finish();
	}
	
	public void LoadPic(){
		int count = mListView.getChildCount();
		for(int i=0; i<count; i++){
			View view = mListView.getChildAt(i);
			ImageView avatarView = (ImageView)view.findViewById(R.id.list_item_avatar);
			ImageView commentView = (ImageView)view.findViewById(R.id.list_comment_imageview);
			TextView messageIdView = (TextView)view.findViewById(R.id.list_item_messageid);
			String avatarUrl = null;
			String commentUrl = null;
			if(messageIdView != null){
				Log.d("commentViewtext", messageIdView.getText().toString()+"");
				avatarUrl = avatarsMap.get(messageIdView.getText());
				commentUrl = messagesMap.get(messageIdView.getText());
			}
			if(avatarUrl != null && !avatarUrl.equals("")){
				Log.d("avatarUrl", avatarUrl);
				asynImageLoader.showImageAsyn(avatarView, Constant.URL_USER_SMALL+avatarUrl, R.drawable.glm_white);
			}
			if(commentUrl != null && !commentUrl.equals("")){
				Log.d("commentUrl", commentUrl+"");
				if(commentView.getVisibility() == View.GONE)
					commentView.setVisibility(View.VISIBLE);
				asynImageLoader.showImageAsyn(commentView, Constant.URL_MESSAGEPIC_SMALL+commentUrl, R.drawable.glm_white);
			}
			else{
//				if(commentView.getVisibility() == View.VISIBLE)
//					commentView.setVisibility(View.GONE);
			}
			
				
		
				
			
			
		}
	}

	public void onRefresh() {
		// TODO Auto-generated method stub
		
	}

	public void onLoadMore() {
		// TODO Auto-generated method stub
		page += 1;
		mHandler.postDelayed(new Runnable() {
			public void run() {
				initUserMessage();
				mAdapter.notifyDataSetChanged();
				onLoad();
			}
		}, 2000);
	}
	
}
